char a[102][103];r[199],s[199];main(n,m,i,j,x,y,e,w,t,l){memset(*a,35,102);for(gets(&n);~scanf("%d%d\n",&n,&m);printf("%d\n",e?e+1:-1)){for(i=1;i<=n;*a[i]=35,gets(a[i]+1),strcpy(a[i]+strlen(a[i]),"#"),j=strchr(a[i],'S'),j?x=a[i],*r=j-x,r[1]=i:0,i++);memset(a[n+1],35,m+2);for(w=t=e=l=0;!e;l++,memcpy(r,s,8*t),t=0){while(~w){x=r[2*w],y=r[2*w--+1];a[y][x]=35;if(a[y][x+1]=='E'||a[y][x-1]=='E'||a[y+1][x]=='E'||a[y-1][x]=='E')e=l;if(a[y][x+1]-35)s[t*2]=x+1,s[t++*2+1]=y,a[y][x+1]=35;if(a[y][x-1]-35)s[t*2]=x-1,s[t++*2+1]=y,a[y][x-1]=35;if(a[y+1][x]-35)s[t*2]=x,s[t++*2+1]=y+1,a[y+1][x]=35;if(a[y-1][x]-35)s[t*2]=x,s[t++*2+1]=y-1,a[y-1][x]=35;}w=t-1;if(!t)break;}}}
